package com.dd.cloud.user.service.patient.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.cloud.user.config.WechatConfig;
import com.dd.cloud.user.config.WechatPayConfig;
import com.dd.cloud.user.entity.patient.PatientUser;
import com.dd.cloud.user.entity.plat.PlatformWechatInfo;
import com.dd.cloud.user.mapper.patient.PatientUserMapper;
import com.dd.cloud.user.req.patient.BindPatientUserWxReq;
import com.dd.cloud.user.res.patient.PatientBindDocRes;
import com.dd.cloud.user.res.patient.PatientUserWxLoginRes;
import com.dd.cloud.user.res.plat.PlatLoginRes;
import com.dd.cloud.user.service.patient.IPatientUserService;
import com.dd.cloud.user.service.plat.IPlatformLoginService;
import com.dd.cloud.user.service.plat.IPlatformWechatInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
 * @author Lx
 * @version 1.0
 */
@Slf4j
@Service
public class PatientUserServiceImpl extends ServiceImpl<PatientUserMapper, PatientUser> implements IPatientUserService {
    @Autowired
    private IPlatformLoginService platformLoginService;
    @Autowired
    private IPlatformWechatInfoService platformWechatInfoService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private WechatConfig wechatConfig;
    @Autowired
    private WechatPayConfig wechatPayConfig;


    /**
     * 微信小程序用户绑定患者用户
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PatientUserWxLoginRes bindPatientUserWx(BindPatientUserWxReq req) {
//        smsComponent.verifyPhoneCode(req.getPhone(), req.getSmsCode());
//        QueryWrapper<PatientUser> qw = new QueryWrapper<>();
//        qw.lambda().eq(PatientUser::getMobileNumber, req.getPhone());
//        qw.lambda().ne(PatientUser::getStatus, UserConstants.PatientUserStatus.DEL);
//        PatientUser patientUser = getOne(qw);
//        if (patientUser == null) {
//            patientUser = new PatientUser();
//            patientUser.setMobileNumber(req.getPhone());
//            patientUser.setStatus(UserConstants.PatientUserStatus.NORMAL);
//            patientUser.setCreateDate(LocalDateTime.now());
//            save(patientUser);
//        }
//        int bind = platformLoginService.bindAppletUser(req.getJsCode(), patientUser.getId(), LoginInfo.UserType.PATIENT);
//        if (bind == 0) {
//            throw new ZekeException(400, "绑定失败");
//        }
//        if (bind == 2) {
//            throw new ZekeException(400, "当前账号被其他微信绑定");
//        }
//        PatientUserWxLoginRes res = new PatientUserWxLoginRes();
//        res.setBind(1);
//        res.setPatientUser(patientUser);
        return null;
    }

    /**
     * 获取患者小程序用户当前登录微信手机号
     *
     * @param req
     * @return
     */
    @Override
    public PlatLoginRes<?> queryPatientUserPhoneWx(BindPatientUserWxReq req, HttpServletRequest request, HttpServletResponse response) {
        return platformLoginService.getWechatUserInfoAppletPhone(req, request, response);
    }

    /**
     * @param openid: 公众号的openid
     * @param docId:
     * @return Boolean
     * @description 通过患者的openid 查询unionid 查询患者自身角色的就诊卡是否绑定医生
     * @author czg
     * @date 2023/10/12 14:00
     */
    @Override
    public Boolean queryIsBindDoc(String openid, Integer docId) {
        QueryWrapper<PlatformWechatInfo> qw = new QueryWrapper<>();
        qw.lambda().eq(PlatformWechatInfo::getOpenid, openid);
        PlatformWechatInfo one = platformWechatInfoService.getOne(qw);
        String unionid;
        /**
         * 查询该openid所属的unionid
         */
        if (one != null && !StringUtils.isBlank(one.getUnionid())) {
            unionid = one.getUnionid();
        } else if (one == null) {
            String accessToken = platformLoginService.getAccessToken();
            String url = String.format(wechatConfig.getGetSubcribeUserInfoUrl(), accessToken, openid);
            log.info(url + "");
            String result = restTemplate.getForObject(url, String.class);
            JSONObject jsonObject = JSONObject.parseObject(result);
            log.info("微信返回:" + jsonObject);
            PlatformWechatInfo wechatUserInfo = new PlatformWechatInfo();
            wechatUserInfo.setCity(jsonObject.getString("city"));
            wechatUserInfo.setCountry(jsonObject.getString("country"));
            wechatUserInfo.setHeadimgurl(jsonObject.getString("headimgurl"));
            wechatUserInfo.setLanguage(jsonObject.getString("language"));
            wechatUserInfo.setNickname(jsonObject.getString("nickname"));
            wechatUserInfo.setOpenid(jsonObject.getString("openid"));
            wechatUserInfo.setProvince(jsonObject.getString("province"));
            wechatUserInfo.setSex(jsonObject.getString("sex"));
            wechatUserInfo.setUnionid(jsonObject.getString("unionid"));
            wechatUserInfo.setCreateDate(LocalDateTime.now());
            wechatUserInfo.setAppid(wechatPayConfig.getAppId());
            platformWechatInfoService.save(wechatUserInfo);
            unionid = wechatUserInfo.getUnionid();
        } else {
            String accessToken = platformLoginService.getAccessToken();
            String url = String.format(wechatConfig.getGetSubcribeUserInfoUrl(), accessToken, openid);
            log.info(url + "");
            String result = restTemplate.getForObject(url, String.class);
            JSONObject jsonObject = JSONObject.parseObject(result);
            log.info("微信返回:" + jsonObject);
            one.setCity(jsonObject.getString("city"));
            one.setCountry(jsonObject.getString("country"));
            one.setHeadimgurl(jsonObject.getString("headimgurl"));
            one.setLanguage(jsonObject.getString("language"));
            one.setNickname(jsonObject.getString("nickname"));
            one.setOpenid(jsonObject.getString("openid"));
            one.setProvince(jsonObject.getString("province"));
            one.setSex(jsonObject.getString("sex"));
            one.setUnionid(jsonObject.getString("unionid"));
            platformWechatInfoService.updateById(one);
            unionid = one.getUnionid();
        }
        if (docId != null) {
            PatientBindDocRes bindDocRes = getBaseMapper().queryPatientIsBindDoc(docId, unionid);
            if (bindDocRes == null) {
                //既没有就诊卡, 也没绑定医生
                return null;
            }
            if (StringUtils.isNotBlank(bindDocRes.getMedId())) {
                //false有就诊卡,但没绑定医生
                //true已绑定医生
                return bindDocRes.getDoctorId() != null;
            } else {
                //既没有就诊卡, 也没绑定医生 有登录信息uniond
                return null;
            }
        }
        return false;
    }

    /**
     * 查询绑定信息
     *
     * @param openid
     * @param docId
     * @return
     */
    @Override
    public PatientBindDocRes queryBindDoc(String openid, Integer docId) {
        QueryWrapper<PlatformWechatInfo> qw = new QueryWrapper<>();
        qw.lambda().eq(PlatformWechatInfo::getOpenid, openid);
        PlatformWechatInfo one = platformWechatInfoService.getOne(qw);
        if (one != null) {
            PatientBindDocRes bindDocRes = getBaseMapper().queryPatientIsBindDoc(docId, one.getUnionid());
            if (bindDocRes != null) {
                return bindDocRes;
            }
        }
        return new PatientBindDocRes();
    }
}
